import Vue from 'vue'
import Router from 'vue-router'

//组件模块
import MainWindow from '@/components/MainWindow'
import * as auth from "@/utils/auth"
import { getInfo } from '@/api/user'
import store from '@/store'
Vue.use(Router)


var router = new Router({
  routes: [
    { path: '/', name: 'MainWindow', component: MainWindow },
    {
      path: '/HelloWorld',
      name: 'HelloWorld',
      component: () => import("@/components/HelloWorld"),
    },
    {
      path: '/ChatWindow',
      name: 'ChatWindow',
      component: () => import("@/components/ChatWindow"),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import("@/components/Login"),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import("@/components/Register"),
    },

  ]
})

router.beforeEach((to, from, next) => {
  var token = auth.getToken()
  //如果没登录,都导向登录页
  if (!token) {
    if (to.path !== '/login') {
      next({ path: '/login' })
    }
    else {
      next();
    }
  }
  else {
    getInfo(token).then(res => {
      if (res.code == 200) {
        store.state.info = res.data
      } else {
        next({ path: '/login' })
      }
    });
    next();
  }
})
/**
 * 跳转登陆页面强制刷新，相当于F5
 */
router.afterEach((to, from) => {
  if (from.path != '/login' && from.path != '/' && to.path == '/login') {
    window.location.reload();
  }
})

export default router;
